package com.zhanghe.handler;

import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import com.zhanghe.annotation.Controller;
import com.zhanghe.annotation.RequestMapping;
import com.zhanghe.util.AnnotationUtil;

public class HttpController {

	private static Map<String,HttpHanlder> httpMapHandler = new HashMap<String, HttpHanlder>();
	
	/**
	 * 
	 * 功能：通过包名加载@controller注解的类<br/>
	 * @param packageName
	 * @exception   无
	 * @since   	首次创建（zhanghe  2018-5-24)<br/>
	 *
	 */
	public static void loadHandlers(String packageName){
		System.out.println("load package:"+packageName);
		AnnotationUtil.scanPackage(packageName, new AnnotationUtil.Callback() {
			
			@Override
			public void callback( File file ,Class<?> clazz ) throws InstantiationException, IllegalAccessException {
				if(clazz!=null && clazz.isAnnotationPresent(Controller.class)){
					System.out.println("load Controller class:"+clazz.getSimpleName());
					Object instance = clazz.newInstance();
					Method[] methods = clazz.getMethods();
					for(Method method:methods){
						if(method.isAnnotationPresent(RequestMapping.class)){
							RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
							for(String url:requestMapping.value()){
								HttpHanlder httpHandler = httpMapHandler.get(url);
								if(httpHandler==null){
									System.out.println("load urlhandler url:"+url+",handler:"+method.getName());
									httpMapHandler.put(url, new HttpHanlder(instance, method));
								}
							}
						}
					}
				}
			}
		});
	}
	public static HttpHanlder getHandler(String url){
		return httpMapHandler.get(url);
	}
}
